<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Models\Configs;
use Illuminate\Http\Request;

class ConfigsController extends Controller
{
    public function index(Request $request)
    {
        $keys = $request->keys ?? null;
        $group = $request->group ?? null;

        if (!$keys && !$group) throw new ApiException('参数不能为空', 501);

        return Configs::query()->when($group, function ($query) use ($group) {
            return $query->where('group', $group);
        })->when($keys, function ($query) use ($keys) {
            return $query->whereIn('key', explode(',', $keys));
        })->get();
    }

    public function update(Request $request)
    {
        /**
         * @var array $data [['key' => 'key1', 'value' => 'value1']]
         */
        $data = $request->all();

        foreach ($data as $key => $value) {
            Configs::where('key', $key)->update(['value' => $value]);
        }
        return $this->successful($data);
    }
}
